#include "SceneObject.h"
#include <glm/gtx/transform.hpp>


SceneObject::SceneObject () : _id (-1), _selected (false), _isVisible (true)
{
	_previewRotateAngle[0] = _previewRotateAngle[1] =
			_previewRotateAngle[2] = 0.0;
	_previewScale[0] = _previewScale[1] = _previewScale[2] = 1.0;
}

SceneObject::~SceneObject ()
{

}

glm::vec3 SceneObject::getLoc () const
{
	return _loc;
}

void SceneObject::setLoc (const glm::vec3 & loc)
{
	_loc = loc;
}

void SceneObject::setName (const QString & name)
{
	_name = name;
}

QString SceneObject::getName () const
{
	return _name;
}

void SceneObject::setColor (const glm::vec3 & color)
{
	_color = color;
}

glm::vec3 SceneObject::getColor () const
{
	return _color;
}

void SceneObject::setId (unsigned int id)
{
	_id = id;
}

unsigned int SceneObject::getId () const
{
	return _id;
}

void SceneObject::setSelected (bool isSelected)
{
	_selected = isSelected;
}

bool SceneObject::isSelected () const
{
	return _selected;
}

void SceneObject::setVisible (bool isVisible)
{
	_isVisible = isVisible;
}

bool SceneObject::isVisible () const
{
	return _isVisible;
}

void SceneObject::rotate (int axis, float angle)
{
	for (int i = 0; i < 3; ++i) {
		if (i == axis)
			_previewRotateAngle[i] = angle;
		else
			_previewRotateAngle[i] = 0.0;
	}
}

void SceneObject::scale (int axis, float ratio)
{
	for (int i = 0; i < 3; ++i) {
		if (i == axis)
			_previewScale[i] = ratio;
		else
			_previewScale[i] = 1.0;
	}
}

void SceneObject::applyPreview ()
{
	_applyRotateMatrix ();
	_applyScaleMatrix ();

	for (int i = 0; i < 3; ++i) {
		_previewRotateAngle[i] = 0.0;
		_previewScale[i] = 1.0;
	}

}

glm::mat4 SceneObject::getPreviewRotateMatrix () const
{
	
	if (_previewRotateAngle[0] != 0.0)
		return glm::rotate<float> (_previewRotateAngle[0], 1.0, 0.0, 0.0);
	else if (_previewRotateAngle[1] != 0.0)
		return glm::rotate<float> (_previewRotateAngle[1], 0.0, 1.0, 0.0);
	else if (_previewRotateAngle[2] != 0.0)
		return glm::rotate<float> (_previewRotateAngle[2], 0.0, 0.0, 1.0);
	return glm::mat4 ();
}

glm::mat4 SceneObject::getPreviewScaleMatrix () const
{
	return glm::scale<float> (_previewScale[0], _previewScale[1],
			_previewScale[2]);
}

QDataStream & operator>> (QDataStream & inStream, SceneObject & object)
{
	inStream >> object._name;
	inStream >> object._color[0] >> object._color[1] >> object._color[2];
	inStream >> object._loc[0] >> object._loc[1] >> object._loc[2];
	// TODO: load _isVisible
	inStream >> object._isVisible;
	
	return inStream;
}

QDataStream & operator<< (QDataStream & outStream, SceneObject & object)
{
	outStream << object._name;
	outStream << object._color[0] << object._color[1] << object._color[2];
	outStream << object._loc[0] << object._loc[1] << object._loc[2];
	outStream << object._isVisible;
	return outStream;
}
